package com.iretailer.report.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.dto.ReHeatChatRule;
import com.iretailer.report.mapper.HeatChatRuleMapper;
import com.iretailer.report.model.HeatChatRule;
import com.iretailer.report.model.enums.ImageTag;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther Bennie
 * @Date 2020/7/1 16:27
 * @Description
 */

@Service
public class HeatChatRuleService extends ServiceImpl<HeatChatRuleMapper, HeatChatRule> {

    @Autowired
    protected ModelMapper modelMapper;


    public boolean saveOrUpdateRule(ReHeatChatRule reHeatChatRule,String user) {
        String id = reHeatChatRule.getId();
        boolean update = StringUtils.isNotBlank(id);
        HeatChatRule heatChatRule = modelMapper.map(reHeatChatRule, HeatChatRule.class);
        if (update) {
            heatChatRule.setUpdateTime(LocalDateTime.now());
        } else {
            heatChatRule.setCreateTime(LocalDateTime.now());
            heatChatRule.setCreateUser(user);
        }
        return super.saveOrUpdate(heatChatRule);
    }


    public PageResult<HeatChatRule> pageHeatChatRule(ReHeatChatRule reHeatChatRule,String userId) {
        QueryOption queryOption = reHeatChatRule.getQuery();
        QueryWrapper<?> queryWrapper = new QueryWrapper<>();
        if(!"Root".equals(userId)){
            queryWrapper.eq("userId",userId );
        }
        Page<?> page = new Page<>();
        queryOption.judge(page, queryWrapper);
        IPage<HeatChatRule> resultPage = baseMapper.pageHeatChatRule(page, null);
        return new PageResult<>(resultPage.getTotal(), resultPage.getRecords());
    }

    public List<HeatChatRule> listHeatChatRule(List<String> mallIds) {
        if(CollectionUtils.isEmpty(mallIds))return new ArrayList<>();
        QueryWrapper<?> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ImageTag", ImageTag.HEAT_CHAT_RULE.getName());
        queryWrapper.in("MallId",mallIds);
        return baseMapper.listHeatChatRule(queryWrapper);
    }

}
